package com.jeesite.common.msg;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import com.aliyun.sdk.gateway.pop.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.utils.StringUtils;
import com.google.gson.Gson;

import darabonba.core.client.ClientOverrideConfiguration;

/**
 * 发送短信（请实现send方法）
 */
public class SmsUtils {

    private final static Logger logger = LoggerFactory.getLogger(SmsUtils.class);

    // 发送短信的方法

    private static boolean sendMsm(Map<String, Object> map, String phone) {
        if (StringUtils.isEmpty(phone))
            return false;
        // 参数1：地域节点
        // 参数2：AccessKey ID
        // 参数3：AccessKey Secret
        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI5t8E6SoGZahrmyYGtANJ",
                "sUH2glPIWxzqASbMPz8AbRM3FnuViq");
        DefaultAcsClient client = new DefaultAcsClient(profile);

        // 设置相关固定参数
        CommonRequest request = new CommonRequest();
        // request.setProtocol(ProtocolType.HTTPS);
        request.setSysMethod(MethodType.POST); // 提交方式，默认不能改
        request.setSysDomain("dysmsapi.aliyuncs.com");// 请求阿里云哪里，默认不能改
        request.setSysVersion("2017-05-25");// 版本号
        request.setSysAction("SendSms");// 请求哪个方法

        // 设置发送相关参数 SMS_468660100
        request.putQueryParameter("PhoneNumbers", phone);// 设置要发送的【手机号】
        request.putQueryParameter("SignName", "星盈IA");// 申请阿里云短信服务的【签名名称】 星盈汇
        request.putQueryParameter("TemplateCode", "SMS_300840023");// 申请阿里云短信服务的【模版中的 模版CODE】SMS_476910682 SMS_476870683

        // 要求传递的code验证码为jason格式，可以使用JSONObject.toJSONString()将map转为json格式
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));

        // 最终发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            logger.error("发送短信失败, errMsg: {}", e.getMessage(), e);
            return false;
        }

    }

    public static void main(String args[]) throws Exception {
    }

    /**
     * 模拟发送短信
     * 请参考 https://api.aliyun.com/product/Dysmsapi
     *
     * @param content 短信内容
     * @param mobile  接受手机号码
     */
    public static boolean send(String tmeId, String content, String mobile,
                               Map<String, String> configs) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(configs.get("accessKey"))
                .accessKeySecret(configs.get("accessKeySecret"))
                // .securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS
                .build());

        try (AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                .serviceConfiguration(Configuration.create()) // Service-level configuration
                .overrideConfiguration(ClientOverrideConfiguration.create()
                        .setEndpointOverride("dysmsapi.aliyuncs.com")
                        .setConnectTimeout(Duration.ofSeconds(30))
                ).build()) {
            // 创建发送短信的请求
            SendSmsRequest request = SendSmsRequest.builder().phoneNumbers(mobile).signName("星盈汇")
                    .templateCode(tmeId).templateParam("{code:\"" + content + "\"}")
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new
                    // HttpHeaders()))
                    .build();
            // 发送短信并获取响应
            CompletableFuture<SendSmsResponse> response = client.sendSms(request);
            SendSmsResponse resp = response.get();
            if (resp.getStatusCode() != 200) {
                logger.error("发送短信失败, errMsg: {}", resp.getBody().getMessage());
            } else {
                logger.info("发送短信成功，Mobile: {}, 模板id: {}, content: {}", mobile, tmeId, content);
            }
        } catch (Exception e) {
            logger.error("发送短信失败, errMsg: {}", e.getMessage(), e);
            return false;
        }
        return true;
    }

}
